/*
 * Copyright (c) 2023 Cshoo Org. All Rights Reserved.
 */

package org.cshoo.tattoo.authorize.app;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.cshoo.tattoo.authorize.api.dto.AddAuthorityReq;
import org.cshoo.tattoo.authorize.api.dto.AuthorityResp;
import org.cshoo.tattoo.authorize.domain.po.Authority;
import org.cshoo.tattoo.authorize.domain.service.AuthorityService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 杨翼
 * @since 1.0
 */
@Service
@Slf4j
public class AuthorityAppService {

    @Resource
    private AuthorityService authorityService;

    /**
     * 创建权限点
     *
     * @param authorityReq 权限点
     */
    public void addAuthority(AddAuthorityReq authorityReq) {
        Authority authority = new Authority();
        BeanUtils.copyProperties(authorityReq, authority);
        authorityService.addAuthority(authority);
    }

    /**
     * 查询所有权限点
     */
    public List<AuthorityResp> findAllAuthority() {
        List<AuthorityResp> result = Lists.newArrayList();
        List<Authority> authorities = authorityService.findAllAuthority();
        authorities.forEach(
                at -> {
                    AuthorityResp atr = new AuthorityResp();
                    result.add(atr);
                }
        );
        return result;
    }

    /**
     * 根据微服务查询权限点，即查询某个微服务下的全部权限点
     *
     * @param microserviceId 微服务id
     * @return 权限点列表
     */
    public List<AuthorityResp> findByMicroserviceId(Long microserviceId) {
        List<AuthorityResp> result = Lists.newArrayList();
        List<Authority> authorities = authorityService.findByMicroserviceId(microserviceId);
        authorities.forEach(at -> {
            AuthorityResp atr = new AuthorityResp();
            BeanUtils.copyProperties(at, atr);
            result.add(atr);
        });
        return result;
    }

    /**
     * 根据角色id查询权限点,即查询某个角色被授权的权限点
     *
     * @param roleId 角色id
     * @return 权限点
     */
    public List<AuthorityResp> findByRoleId(Long roleId) {
        List<Authority> authorities = authorityService.findByRoleId(roleId);
        List<AuthorityResp> result = Lists.newArrayList();
        authorities.forEach(aut -> {
            AuthorityResp authorityResp = new AuthorityResp();
            BeanUtils.copyProperties(aut, authorityResp);
            result.add(authorityResp);
        });
        return result;
    }

    /**
     * 刷新权限点
     * 将传入的微服务的权限点载入到数据库中
     *
     * @param microserviceId 微服务id
     */
    public void refreshAuthorities(Long microserviceId) {
        authorityService.refreshAuthorities(microserviceId);
    }

    /**
     * 确定访问范围
     *
     * @param id          id
     * @param accessScope access范围
     */
    public void fixAccessScope(Long id, Integer accessScope) {
        authorityService.fixAccessScope(id, accessScope);
    }
}
